package com.atguigu.study.service.impl;

import com.atguigu.study.annotations.MyRedisCache;
import com.atguigu.study.entities.User;
import com.atguigu.study.mapper.UserMapper;
import com.atguigu.study.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
* @author 48138
* @description 针对表【t_user(用户表)】的数据库操作Service实现
* @createDate 2025-07-31 08:32:35
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService {

    public static final String CACHE_KEY_USER = "user";

    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public boolean save(User user) {
        boolean retValue = false;
        log.info("插入之前user：{}",user);
        retValue = super.save(user);
        log.info("插入之后user:{}",user);
        log.info("=====================");
        if(retValue){
            user= this.userMapper.selectById(user.getId());

            String key = CACHE_KEY_USER + user.getId();

            redisTemplate.opsForValue().set(key,user);
        }
        return retValue;
    }
    /*@Override
    public User getById(Serializable id) {
        User user = null;
        //缓存key
        String key = CACHE_KEY_USER + id;

        //1.查询redis
        user = (User)redisTemplate.opsForValue().get(key);
        //2.redis有直接返回，redis无则进一步查询mysql
        if(user==null){
            //从mysql内查出来user
            user = this.userMapper.selectById(id);
            //3、mysql有，redis无
            if(user!=null){
                //把mysql的数据捞出来写进redis，方便下次查询使用，再返回给请求者
                redisTemplate.opsForValue().set(key,user);
            }
        }
        return user;
    }*/


    @Override
    @MyRedisCache(keyPrefix = "user",matchValue = "#id")
    public User getById(Serializable id) {
        return this.userMapper.selectById(id);
    }
}




